package com.nxmu.hire.controller;

import com.nxmu.hire.common.constant.UserConstant;
import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.common.util.CookieUtil;
import com.nxmu.hire.common.util.ResponseResult;
import com.nxmu.hire.model.User;
import com.nxmu.hire.service.UserService;
import com.nxmu.hire.vo.LoginReqVo;
import com.nxmu.hire.vo.LoginResVo;
import com.nxmu.hire.vo.ModifyPasswordReqVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public ResponseResult login(@Valid @RequestBody LoginReqVo loginReqVo, HttpServletRequest request, HttpServletResponse response){
        List<User> users = userService.getUserByUserIdAndPassword(loginReqVo);
        if (users != null && !users.isEmpty()){
            request.getSession().setAttribute(UserConstant.SESSION_USER,users.get(0));
            CookieUtil.addObjectToCookie(response,UserConstant.SESSION_USER,users.get(0));
            LoginResVo loginResVo = new LoginResVo();
            loginResVo.setUserId(users.get(0).getUserId());
            loginResVo.setUserName(users.get(0).getUserName());
            return ResponseResult.success(loginResVo);
        }
        return ResponseResult.fail("用户名或密码错误");
    }

    @ApiOperation(value = "修改密码")
    @PostMapping(value = "/modifyPassword")
    public ResponseResult modifyPassword(@Valid @RequestBody ModifyPasswordReqVo modifyPasswordReqVo) {
        try {
            userService.modifyPassword(modifyPasswordReqVo);
        } catch (ServiceException e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

    @ApiOperation(value = "注销")
    @GetMapping(value = "/logout")
    public ResponseResult logout(HttpServletRequest request,HttpServletResponse response) {
        request.getSession().setAttribute(UserConstant.SESSION_USER,null);
        Cookie[] cookies = request.getCookies();
        return ResponseResult.success();
    }

}
